var flowRows = []
var userRows = []
$(function () {
  dateRange()
  jQuery.validator.addMethod("agentUserCheck", function (value, element) {
    return Boolean(userRows.length)
  }, "请选择代理人员");

  $("#editForm").validate({
    onkeyup: false,
    ignore:[],
    rules: {
      dateRange: {
        required: true
      },
      agentUser: {
        agentUserCheck: true
      },

    },
    messages: {
      dateRange: {
        required: "请选择日期范围"
      },
    },
    errorPlacement: function (error, element) {
      if (element[0]['name'] === 'agentUser') {
        error.appendTo(element.parent().find("#validate-result-object"));
      } else {
        error.insertAfter(element);
      }
    },
    focusCleanup: true
  });
})

function selectFlow() {
  var url = './flowTable';
  var options = {
    title: '选择代理流程',
    url: url,
    callBack: doSubmitFlow
  };
  var agentIds = []
  flowRows.forEach(function (flow) {
    agentIds.push(flow.key)
  })
  $.modal.openOptionsInitData(options, agentIds);
}

function doSubmitFlow(index, layero) {
  var iframeWin = window[layero.find('iframe')[0]['name']];
  var rows = iframeWin.$('#bootstrap-table').bootstrapTable('getSelections');
  flowRows = []
  rows.forEach(function (row) {
    flowRows.push({
      name: row.name_,
      key: row.key_
    })
  })
  formatSr()
  layer.close(index);
}

function selectUser() {
  var url = './userTable';
  var options = {
    title: '选择代理人员',
    url: url,
    callBack: doSubmitUser
  };
  var userIds = []
  userRows.forEach(function (user) {
    userIds.push(user.id)
  })
  $.modal.openOptionsInitData(options, userIds);
}

function doSubmitUser(index, layero) {
  var iframeWin = window[layero.find('iframe')[0]['name']];
  var rows = iframeWin.$('#bootstrap-table').bootstrapTable('getSelections');
  userRows = []
  rows.forEach(function (row) {
    userRows.push({
      name: row.username,
      id: row.user_id
    })
  })
  formatSr()
  layer.close(index);
}

function formatSr() {
  var userTemp = []
  userRows.forEach(function (user) {
    userTemp.push(user.name || user.receiverUserName)
  })
  var flowTemp = []
  flowRows.forEach(function (flow) {
    flowTemp.push(flow.name)
  })
  $("#agentUser").html(userTemp.length == 0 ? "未选择" : userTemp.join("，"))
  $("#agentPro").html(flowTemp.length == 0 ? "未选择" : flowTemp.join("，"))
}

function dateRange() {
  layui.use('laydate', function () {
    var laydate = layui.laydate;
    var startDate = laydate.render({
      elem: '#dateRange',
      theme: 'molv',
      trigger: 'click',
      range: '至',
      done: function (value, date) {

      }
    });
  });
}

function submitHandler() {

  if ($.validate.form()) {
    var agencyFlowKey = []
    var agencyFlowName = []
    flowRows.forEach(function (flow) {
      agencyFlowKey.push(flow.key)
      agencyFlowName.push(flow.name)
    })
    var targetUserId = []
    var targetUserName = []
    userRows.forEach(function (user) {
      targetUserId.push(user.id)
      targetUserName.push(user.name)
    })
    var dateRange = $('#dateRange').val().split(' 至 ')
    var params = {
      flowList: flowRows,
      agencyFlowKey: agencyFlowKey.length == 0 ? "" : agencyFlowKey.join(","),
      agencyFlowName: agencyFlowName.length == 0 ? "" : agencyFlowName.join(","),
      userList: userRows,
      targetUserId: targetUserId.length == 0 ? "" : targetUserId.join(","),
      targetUserName: targetUserName.length == 0 ? "" : targetUserName.join(","),
      startDatetime: dateRange[0] + ' 00:00:00',
      endDatetime: dateRange[1] + ' 00:00:00',
    }
    var option = {
      url: api + '/scabpm/bpm/userAgencyConfig/save',
      type: 'POST',
      data: JSON.stringify(params),
      contentType: 'application/json',
      dataType: "json",
      beforeSend: function () {
        $.modal.loading("正在保存中，请稍后...");
      },
      success: function (res) {
        $.modal.closeLoading()
        if (res.code == '200') {
          $.modal.confirm(res.msg+"，是否继续操作？", function () {
            $('#dateRange').val('')
            flowRows = []
            userRows = []
          });
          layer.confirm(res.msg+"，是否继续操作？", {
            icon: 3,
            title: "系统提示",
            btn: ['确认', '取消']
          }, function (index) {
            $('#dateRange').val('')
            $("#agentUser").html('')
            $("#agentPro").html('')
            flowRows = []
            userRows = []
            layer.close(index);
            parent.window.loadList()
          },function (index) {
            layer.close(index);
            $.modal.close()
            parent.window.loadList()
          });
        } else {
          $.modal.alertError(res.msg)
        }
      }
    }
    $.ajax(option)
  }

}